package com.bridgeQQ.client.control.commands.msg
{
	import com.bridgeQQ.client.constant.MsgCont;
	import com.bridgeQQ.client.control.ApplicationController;
	import com.bridgeQQ.client.control.MessageManager;
	import com.bridgeQQ.client.control.commands.BaseRespond;
	import com.bridgeQQ.client.core.ICommand;
	import com.bridgeQQ.client.core.message.IBridgeRelation;
	import com.bridgeQQ.client.core.message.IMessageDisplay;
	import com.bridgeQQ.client.core.message.IMessageRelation;
	import com.bridgeQQ.client.events.SendEvent;
	import com.bridgeQQ.client.util.MessageUtil;
	
	import mx.controls.Alert;
	import mx.messaging.messages.IMessage;
	
	public class SendMsgCommand extends BaseRespond implements ICommand
	{
		private var msgIDs:Array;
		
		private var mm:MessageManager;
		
		public function SendMsgCommand(info:Object, target:Object, ...params)
		{
			super(info, target);
		}
		
		public override function execute() : void
		{
			var mr:IMessageRelation = info.relation;
			var destinations:Array = mr ? (mr is IBridgeRelation ?
			    IBridgeRelation(mr).nearRelation.source :  mr.getAllRelations().source) : null;
			if(destinations == null && info.destination)
			{
				destinations = [info.destination];
			}
			var body:String = info.body;
			var type:String = info.type ? info.type : MsgCont.MSG_TYPE_NORMAL;
			var msg:IMessage = info.msg ? info.msg : MessageUtil.createMessage(body, "", type);
			if(destinations == null)
			{
				destinations = [msg.headers.destination];
			}
			var connectionType:String =  mr is IBridgeRelation ? "peer" : null;
			mm = ApplicationController.controller.getSubController("messageManager");
			mm.addEventListener(SendEvent.SUCCESS, onSendResult);
			mm.addEventListener(SendEvent.ERROR, onSendError);
			mm.addEventListener(SendEvent.TIME_OUT, onSendError);
			var md:IMessageDisplay = info.relation as IMessageDisplay;
			if(md)
			{
				md.receiveMsg(msg, false);
			}
			msgIDs = mm.sendMsg(msg, destinations, connectionType);
		}
		
		private function onSendResult(event:SendEvent):void
		{
			if(msgIDs.indexOf(event.sendID) >= 0)
			{
				mm.removeEventListener(SendEvent.SUCCESS, onSendResult);
				mm.removeEventListener(SendEvent.ERROR, onSendError);
				mm.removeEventListener(SendEvent.TIME_OUT, onSendError);	
				mm = null;	
				createRespondInfo(false, null);
			}	
		}
		
		private function onSendError(event:SendEvent):void
		{
			mm.removeEventListener(SendEvent.SUCCESS, onSendResult);
			mm.removeEventListener(SendEvent.ERROR, onSendError);
			mm.removeEventListener(SendEvent.TIME_OUT, onSendError);		
			var sendID:String = event.sendID;
			if(msgIDs.indexOf(sendID) >= 0)
			{
				createRespondInfo(true, null)
				Alert.show("send error");
			}
		}
	}
}